package com.example.wheelguide;

import java.io.Serializable;
import java.util.ArrayList;

import android.content.Context;
import android.widget.Button;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;


public class Database implements Serializable{
	ArrayList<Profile> profiles_;
	final static String DBNAME = "wheelGuide.db";
	ObjectContainer db_;
	Context ctx_;
	
	public Database(Context ctx) {
		this.ctx_=ctx;
		profiles_= new ArrayList<Profile>();
		loadDB();
		showAllProfiles();
	}
	
	private void openDB()
	{ 
		try
		{
			db_ = Db4o.openFile(db4oDBFullPath(ctx_));
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		System.out.println("DB geoeffnet");
	}
	private void closeDB()
	{
		try
		{
			db_.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		System.out.println("DB geschlossen");
	}
	
	/*
	 * Diese Funktion prueft ob ein Profil vorhanden ist.
	 * 
	 * Return Werte:
	 * Wenn Profil vorhanden return true
	 * Wenn Profil nicht vorhanden return false 
	 */
	public boolean checkProfil()
	{
		
		if(profiles_.isEmpty())
		{
			System.out.println("Keine Profile Vorhanden");
			return false;
			
		}
		else
		{
			System.out.println(profiles_.size()+" Profile Vorhanden");
			return true;
			
		}
	}
	
	public boolean addProfil(Profile p)
	{
		try
		{
			System.out.println("Add Profile");
			profiles_.add(p);
			showAllProfiles();
			openDB();
			db_.store(profiles_);
			db_.commit();
			closeDB();
			System.out.println(p.getProfilname_()+" gespeichert");
			return true;
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		return false;
	}

	
	private String db4oDBFullPath (Context ctx) {
        return  ctx.getDir ("Datenbank", Context.MODE_PRIVATE) + "/"+ DBNAME; 
    }
	
	private boolean loadDB()
	{
		try
		{ 	
			
			System.out.println("Database.loadDB()1");
			openDB();
			
			ObjectSet <Profile> os=db_.queryByExample(Profile.class);
			
			
			
			for(Profile p:os)
	        {
	        	System.out.println(p.getProfilname_());
	        	System.out.println("Database.loadDB()2");
	            profiles_.add(p);
	            System.out.println("Database.loadDB()3");
	        }
			
			closeDB();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return true;
	}

	public void showAllProfiles()
	{
		for(int i=0;profiles_.size()<i;i++)
		{
			System.out.println("Profil:"+ profiles_.get(i).getProfilname_());
		}
	}
	
}
